package applib

import (
	"bufio"
	"encoding/json"
	"fmt"
	"github.com/urfave/cli/v2"
	"os"
)

var (
	BuildTime string
	Version   = "1.0.0"
)

func Do() {
	app := cli.NewApp()
	app.Name = "app_list"
	app.Version = fmt.Sprintf("%s build:%s", Version, BuildTime)
	app.Description = "获取pc上的软件信息，包括：软件安装列表、检查文件是否存在、检查进程是否存在等 \n 程序访问注册表，请注意调用权限"
	app.Flags = []cli.Flag{
		&cli.BoolFlag{
			Name:    "appList",
			Aliases: []string{"al"},
			Usage:   "默认执行该参数，返回cp上已安装的软件列表，可能不全。遇到采集遗漏的请保留现场环境，联系管理员更新插件做适配，谢谢",
		},
		&cli.StringFlag{
			Name:    "exe",
			Aliases: []string{"e"},
			Usage:   "检查指定路径下是否存在某个文件，并返回文件的MD5。适用于特殊软件检查",
		},
	}
	app.Action = func(ctx *cli.Context) error {
		var (
			exeStr string
			err    error
			md5    string
			bs     []byte
		)
		w := bufio.NewWriter(os.Stdout)
		if ctx.IsSet("exe") {
			exeStr = ctx.String("exe")
			if md5, err = CheckByPath(exeStr); err != nil {
				return cli.Exit(err, 1)
			}
			w.WriteString(md5 + "\n")
			w.Flush()
		} else {
			li, err := getList()
			if err != nil {
				return err
			}
			if bs, err = json.Marshal(li); err != nil {
				return err
			}
			w.WriteString(string(bs) + "\n")
			w.Flush()
		}
		return nil
	}

	sub := cli.Command{}
	sub.Name = "process"
	sub.Aliases = []string{"pro"}
	sub.Description = "检查进程信息，返回bool和number，number表示系统中有多少个这样名称的进程；bool表示是否存在一个进程是指定路径下的程序创建的"
	sub.Flags = []cli.Flag{
		&cli.StringFlag{
			Name:     "path",
			Aliases:  []string{"p"},
			Usage:    "指定进程exe执行文件所在的路径",
			Required: true,
		},
		&cli.StringFlag{
			Name:     "name",
			Aliases:  []string{"n"},
			Usage:    "指定进程名称",
			Required: true,
		},
	}
	sub.Action = func(ctx *cli.Context) error {
		var (
			p string
			n string
		)
		p = ctx.String("path")
		n = ctx.String("name")
		is, num, err := checkProcess(n, p)
		if err != nil {
			return err
		}
		r := CheckProcessResult{
			Name:    n,
			Path:    p,
			IsExist: is,
			Num:     num,
		}
		var bs []byte
		if bs, err = json.Marshal(r); err != nil {
			return err
		}
		w := bufio.NewWriter(os.Stdout)
		w.WriteString(string(bs) + "\n")
		w.Flush()
		return nil
	}
	app.Commands = append(app.Commands, &sub)
	if err := app.Run(os.Args); err != nil {
		fmt.Printf("命令行调用错误：%s ，请查看帮助文档", err.Error())
	}

}
